# LuckPay Web Manage System
#
# Copyright (c) 2016 Lucky Byte, Inc.
#
express = require 'express'
pgsql   = require 'pg'
uuid    = require 'uuid'
router = express.Router()
module.exports = router

router.all '/', (req, res, next) ->
    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    where_clause = "(
        r.name like $1 or r.notes like $1
    )"
    # 查询记录总数
    await client.query "select count(*) as count from web_roles as r
        where #{ where_clause }", [
            '%' + res.locals.keyword + '%'
        ], defer err, result
    if err then done(client); return next(err)
    res.locals.total = result.rows[0].count

    # 查询当前页面中显示的记录
    await client.query "select r.*, count(u.role) as n_users
        from web_roles as r left join web_users as u on r.uuid = u.role
        where #{ where_clause }
        group by r.serial, r.uuid
        order by r.serial offset $2::int limit $3::int", [
            '%' + res.locals.keyword + '%',
            res.locals.offset,
            res.locals.page_rows
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.render 'roles/index', records : result.rows


router.get '/new', (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '新增菜单权限配置'
    res.render 'roles/new', record: {}


router.post '/new', (req, res, next) ->
    for k in ['name']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "insert into web_roles ( uuid, name, root, permission, notes )
            values ( $1, $2, $3, $4, $5 )", [
            uuid.v4(),
            req.body.name,
            req.body.root is 'on',
            req.body.permission or '',
            req.body.notes,
        ], defer err, result
    if err then done(client); return next(err)
    done()
    res.redirect '/roles'


router.get '/edit/:id', (req, res, next) ->
    res.locals.breadcrumbs.push 'title': '配置菜单权限'

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    # 可以通过序号和 UUID 之一来查询
    sql = "select * from web_roles where serial = $1::int"
    if req.params.id.indexOf('-') > 0
        sql = "select * from web_roles where uuid = $1"

    await client.query sql, [ req.params.id ], defer err, result
    if err then done(client); return next(err)
    done()
    if result.rows.length != 1
        return next(new Error("查无此记录[#{req.params.id}]"))

    record = result.rows[0]
    record.permission = JSON.stringify(record.permission)
    res.render 'roles/edit', record: record


router.post '/edit', (req, res, next) ->
    for k in ['serial', 'uuid', 'name', 'permission']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err)

    await client.query \
        "select permission from web_roles where serial = $1 and uuid = $2", [
            req.body.serial, req.body.uuid,
        ], defer err, result
    if err then done(client); return next(err)
    if result.rows.length == 0
        done()
        return next(new Error('未找到原始记录'))

    # 记住之前的权限值
    permission = result.rows[0].permission

    await client.query \
        "update web_roles set name = $1, root = $2,
            permission = $3, notes = $4
        where serial = $5 and uuid = $6", [
            req.body.name,
            req.body.root is 'on',
            req.body.permission,
            req.body.notes,
            req.body.serial,
            req.body.uuid,
        ], defer err, result
    if err then done(client); return next(err)

    # 如果权限值修改了，则退出所有与此权限关联的用户登录
    if permission != req.body.permission
        await client.query "delete from web_session as s
            where s.sess#>>'{userinfo, uuid}' in
                (select uuid from web_users as u where u.role = $1)", [
                req.body.uuid,
            ], defer err, result
        if err then done(client); return next(err)

    done()
    res.redirect '/roles'


router.post '/delete', (req, res, next) ->
    res.type 'json'
    for k in ['serial', 'uuid']
        return next(new Error("请求缺少参数[#{k}]")) if not req.body[k]

    await pgsql.connect settings.pgsql_url, defer err, client, done
    if err then done(client); return next(err);

    await client.query \
        "delete from web_roles where serial = $1 and uuid = $2", [
            req.body.serial, req.body.uuid,
        ], defer err, result
    if err then done(client); return next(err);
    done()
    res.json succ: true, redirect: '/roles'
